#include "faceserver.h"
#include "ui_faceserver.h"
#include "facemanage.h"
#include <QSqlTableModel>
faceServer::faceServer(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::faceServer)
{
    ui->setupUi(this);

    connect(&serverTcp,&QTcpServer::newConnection,this,&faceServer::connectFunct);

    serverTcp.listen(QHostAddress::Any,777);
    recvSize=0;
}

faceServer::~faceServer()
{
    delete ui;
}

void faceServer::connectFunct()
{
    qDebug()<<"new connect";
    clienTcp = serverTcp.nextPendingConnection();
    connect(clienTcp,&QTcpSocket::readyRead,this,&faceServer::readDataFunct);
}

void faceServer::readDataFunct()
{
    QDataStream stream(clienTcp);
    stream.setVersion(QDataStream::Qt_5_14);
    if(recvSize==0)
    {
        if(clienTcp->bytesAvailable()<(quint64)sizeof(recvSize)) return;
        stream >> recvSize;
    }
    if(clienTcp->bytesAvailable()<recvSize) return;
    QByteArray buf;
    stream >> buf;
    recvSize=0;
    if(buf.size()==0) return;
    QPixmap pmap;
    pmap.loadFromData(buf,"jpg");

    pmap =pmap.scaled(ui->showHead->size());
    ui->showHead->setPixmap(pmap);

    cv::Mat receimg;
    std::vector<uchar> decode;
    decode.resize(buf.size());
    memcpy(decode.data(),buf.data(),buf.size());
    receimg = cv::imdecode(decode, cv::IMREAD_COLOR);
    int faceid  = fmobj.query_face(receimg);
    qDebug()<<"faceif="<<faceid<<endl;
    QSqlTableModel mod;
    mod.setTable("employee");
    mod.setFilter(QString("faceID = %1").arg(faceid));
    mod.select();
    QString sendjson=QString("{\"job\":\"%1\", \"name\":\"%2\", \"part\":\"%3\", \"time\":\"%4\"}").\
            arg(mod.data(mod.index(0,3)).toString()).arg(mod.data(mod.index(0,1)).toString())\
            .arg(mod.data(mod.index(0,2)).toString()).arg(mod.data(mod.index(0,4)).toString());

    qDebug()<<sendjson;
    clienTcp->write(sendjson.toUtf8());

}

